﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Configuration;
using System.Data.SqlClient;
using STLGROUP.Layers.DataAccessLayers;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using STLGROUP.Layers.Common;

namespace QuanLyBanHang.SystemForms
{
    public partial class frmBackup : STLGROUP.Layers.Presentations.FormBase.frmBase
    {

        #region Variables

        private string _connectionString = "";
        private SqlConnection _sqlConnection = null;
        private SqlCommand _sqlCommand = null;
        private DataTable _dataTable = null;
        //private QuanLyBanHangEntities _ctx = new QuanLyBanHangEntities();
        private string _server;

        #endregion

        #region Constructors

        public frmBackup()
        {
            InitializeComponent();
        } 

        #endregion

        #region Private Methods

        #region ShowFiles

        private void ShowFiles(string folder)
        {
            try
            {
                lvwFiles.Items.Clear();

                DirectoryInfo directoryInfo = new DirectoryInfo(folder);
                int stt = 0;
                
                foreach (FileInfo fileInfo in directoryInfo.GetFiles())
                {
                    if (fileInfo.Extension.CompareTo(".bak") == 0)
                    {
                        stt++;

                        ListViewItem item = new ListViewItem(new string[]{"",stt.ToString(),fileInfo.Name,fileInfo.CreationTime.ToString("dd/MM/yyyy"),(fileInfo.Length/1024/1024).ToString("N0") + " MB"});

                        lvwFiles.Items.Add(item);
                        
                    }
                }
            }
            catch (Exception)
            {

            }
        } 

        #endregion

        #region Browser

        private void Browser()
        {
            FolderBrowserDialog open = new FolderBrowserDialog();
            DialogResult result = open.ShowDialog();

            if (result == DialogResult.OK)
            {
                txtFolder.Text = open.SelectedPath;
                ShowFiles(txtFolder.Text);

                ColorToListView(Color.Blue, Color.Chocolate, lvwFiles);
                lvwFiles.Refresh();
            }
        } 

        #endregion

        #region DefaultFile

        private void DefaultFile()
        {
            txtDefaultFile.Text = cbxDatabase.Text + DateTime.Now.ToString("_yyyy_MM_dd-hh-mm-ss-tt");
        } 

        #endregion

        #region ConnectionString

        private string ConnectionString(string serverName, string databaseName)
        {
            return string.Format("server={0};database={1};Integrated Security=true;", serverName, databaseName);
        } 

        #endregion

        #region ConnectToServer

        private void ConnectToServer(string serverName)
        {
            try
            {
                _connectionString = ConnectionString(serverName, "master");
                _sqlConnection = new SqlConnection(_connectionString);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Lỗi");
            }
        } 

        #endregion

        #region GetDataTable

        private DataTable GetDataTable(string commandText)
        {    
            try
            {
                DataTable dataTable = new DataTable();
                _sqlCommand = new SqlCommand();
                _sqlCommand.CommandText = commandText;
                _sqlCommand.Connection = _sqlConnection;
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(_sqlCommand);
                sqlDataAdapter.Fill(dataTable);

                return dataTable;
            }
            catch
            {
#if DEBUG
               // MessageBox.Show(ex.ToString(), "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
#else
                MessageBox.Show("Kết nối với máy chủ không thành công, vui lòng nhập lại địa chỉ máy chủ.", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif

            }
            return null;
        }

        #endregion

        #region AddItems

        private void AddItems(ComboBox cbo, DataTable dataTable)
        {
            try
            {
                cbo.DataSource = dataTable;
                cbo.DisplayMember = "name";
                cbo.ValueMember = "name";

                DefaultFile();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Lỗi");
            }
        }

        #endregion

        #region Server_Refresh

        private void Server_Refresh()
        {
            try
            {
                //_server = _ctx.Connection.DataSource;

                _server = Cache.Context.Connection.DataSource;
                ConnectToServer(_server);
                _dataTable = GetDataTable("Select name From sysdatabases");
                AddItems(cbxDatabase, _dataTable);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Lỗi");
            }
        } 

        #endregion

        #region Backup

        private void Backup_DB(string database)
        {
            if (txtFolder.Text != string.Empty)
            {
                string path = txtFolder.Text;

                if (rdoFileDefault.Checked)
                {
                    path += "\\" + txtDefaultFile.Text + ".bak";
                }
                else
                {
                    if (string.IsNullOrEmpty(txtFileName.Text))
                    {
                        MessageBox.Show("Vui lòng nhập vào tên file dùng để sao lưu.", "Lỗi");
                        return;
                    }
                    else
                    {
                        path += "\\" + txtFileName.Text + ".bak";
                    }
                }

                try
                {
                    Server server = new Server(_server);
                    Backup backupMgr = new Backup();
                    backupMgr.Devices.AddDevice(path, DeviceType.File);
                    backupMgr.Database = database;
                    backupMgr.Action = BackupActionType.Database;
                    backupMgr.SqlBackup(server);

                    MessageBox.Show("Sao lưu dữ liệu thành công lúc " + string.Format(DateTime.Now.ToString("hh:mm:ss tt {0} dd {1} MM {2} yyyy"), "ngày", "tháng", "năm"), "Thông tin",
                                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Chú ý:\n Thư mục lưu trữ không phải là thư mục hệ thống\n và không phải ổ đĩa cài hệ điều hành"+"\n"+ex.Message);
                }
            }
            else
            {
                MessageBox.Show("Bạn vui lòng chọn thư mục chứa tập tin sao lưu *.bak", "Thông báo");
            }
        } 

        #endregion

        #region ColorToListView

        private void ColorToListView(Color color1, Color color2, ListView lvw)
        {
            for (int i = 0; i < lvw.Items.Count; i++)
            {
                if (i % 2 == 0)
                {
                    lvw.Items[i].BackColor = Color.Red;
                }
                else
                {
                    lvw.Items[i].BackColor = Color.Yellow;
                }
            }
        } 

        #endregion

        #endregion

        #region Events

        private void btxBrowser_Click(object sender, EventArgs e)
        {
            Browser();
        }

        private void txtFolder_TextChanged(object sender, EventArgs e)
        {
            ShowFiles(txtFolder.Text);
        } 

        private void btxBackup_Click(object sender, EventArgs e)
        {
            Backup_DB(cbxDatabase.SelectedValue.ToString());
            ShowFiles(txtFolder.Text);
        }

        private void btxReset_Click(object sender, EventArgs e)
        {
            txtFolder.Text = txtFileName.Text = string.Empty;
        }

        private void btxExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cbxDatabase_SelectionChangeCommitted(object sender, EventArgs e)
        {
            DefaultFile();
        }

        private void rdoFileName_CheckedChanged(object sender, EventArgs e)
        {
            txtFileName.Enabled = rdoFileName.Checked;
        }

        private void frmBackup_Load(object sender, EventArgs e)
        {
            Server_Refresh();
        }

        //restore
        private void btnRestore_Click(object sender, EventArgs e)
        {
            frmRestore frm = new frmRestore();
            frm.ShowDialog();
        }

        #endregion
    }
}
